#!/usr/bin/python3.6

# Script to generate repository configuration for rpmdistro-repoquery
# Author: Neal Gompa
# License: MIT
# See LICENSE for license information

import argparse
import datetime
import os
import shutil
import subprocess
import sys
import tempfile

import rpm


def generate_dnf_config(distro, releasever, output_filepath):
    with open("./distros/{0}.conf".format(distro)) as dnfconf_file:
        dnf_conf = dnfconf_file.read()
        releasever_tuple = tuple(releasever.split(".", 1))
        if distro == "sle-bci" and len(releasever_tuple) > 1:
            releaseversp = "{}-SP{}".format(releasever_tuple[0], releasever_tuple[1])
        else:
            releaseversp = "{}".format(releasever_tuple[0])
        # Mageia needs proper arch setup for repos
        if distro == "mageia":
            dnf_conf = dnf_conf.replace("$distarch", rpm.expandMacro("%{_target_cpu}"))
        if distro == "sle-bci":
            dnf_conf = dnf_conf.replace("$releaseversp", releaseversp)
        with open(output_filepath, 'w') as gen_dnfconf_file:
            gen_dnfconf_file.write(dnf_conf)
            gen_dnfconf_file.flush()
    return


parser = argparse.ArgumentParser(description="Creates dnf.conf for rpmdistro-repoquery")

parser.add_argument("-d", "--distro", help="Distribution base to use", dest="distro", choices=["fedora", "mageia", "opensuse-leap", "opensuse-tumbleweed", "centos", "centos-stream", "rhel-ubi", "sle-bci"], required=True)
parser.add_argument("-r", "--releasever", help="Distribution release version", dest="releasever", required=True)
parser.add_argument("-o", "--output-conf-file", help="File path to write DNF config file", dest="outputpath", required=True)

args = parser.parse_args()

# Check to ensure we're *not* running as root
if os.geteuid() == 0:
    sys.exit("This script must never be run as root!")

# Make the config file
dnf_config = generate_dnf_config(args.distro, args.releasever, args.outputpath)
